package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"
)

func main() {
	http.HandleFunc("/hello", sayHello);
	http.HandleFunc("/tiao_zhuan", sayHello2);
	http.HandleFunc("/acay", acay);
	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("http server failed, err:%v\n", err)
		return
	}
}

func sayHello(w http.ResponseWriter, r *http.Request)  {
	defer r.Body.Close()
	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Set("Access-Control-Allow-Credentials", "true")    //设置为true，允许ajax异步请求带cookie信息
	w.Header().Set("Access-Control-Allow-Origin",r.Header.Get("Origin"))
	w.Header().Set("Access-Control-Allow-Headers","Accept,,Accept-Language,Content-Language,Last-Event-ID,Content-type")
	// 2. 请求类型是application/json时从r.Body读取数据
	b, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println("read request.Body failed, err:%v\n", err)


		return
	}
	fmt.Println("获取数据为：")
	fmt.Println(string(b))
	answer := `{"status": "ok"}`
	w.Write([]byte(answer))
	//http.Redirect(http.StatusMovedPermanently,"http://www.baidu.com");
	http.Redirect(w,r,"http://www.baidu.com",http.StatusMovedPermanently)
}
func sayHello2(w http.ResponseWriter, r *http.Request)  {
	w.Header().Set("Access-Control-Allow-Origin", "*")             //允许访问所有域
	w.Header().Set("Access-Control-Allow-Credentials", "true")    //设置为true，允许ajax异步请求带cookie信息
	w.Header().Set("Access-Control-Allow-Origin",r.Header.Get("Origin"))
	w.Header().Set("Access-Control-Allow-Headers","content-type")
	http.Redirect(w,r,"http://www.baidu.com",http.StatusMovedPermanently)
}

func acay(w http.ResponseWriter, r *http.Request)  {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	copy_w:=w;
	name:="王彦超";
	name2:=&name;
	fmt.Println(name)
	go acay_fun(copy_w,name2);
	time.Sleep(time.Second*10);
	fmt.Println(name)
}

func acay_fun(w http.ResponseWriter,name *string) {
	//fmt.Println("开始延迟")
	time.Sleep(time.Second*5);
	//fmt.Println("执行开始");
	*name="洛洛洛";
	fmt.Println(name);
	w.Write([]byte("终于到我了，啊啊啊！"));
	fmt.Println("执行完毕");
}
